package org.bizming.medicine.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.bizming.base.service.SqlHelper;
import org.bizming.medicine.model.ShipmentMedicine;
import org.bizming.medicine.model.ext.ShipmentExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class ShipmentMysqlDao implements ShipmentDao {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private JdbcTemplate jdbcTemplate;

	private SqlHelper sqlHelper;

	private String tableName = "shipmentmedicine";

	public boolean add(ShipmentMedicine t) {
		List<Object> values = new ArrayList<Object>();
		String sql = sqlHelper.sqlAdd(t, values, getTableName());
		logger.info(sql);

		Object[] o = values.toArray();
		int affectRow = jdbcTemplate.update(sql, o);

		sqlHelper.clear(values);
		sqlHelper.clear(o);

		if (affectRow > 0) {
			return true;
		} else {
			return false;
		}
	}

	public List<ShipmentExt> selectList() {
		String sql = sqlHelper.sqlSelectList(ShipmentMedicine.class, getTableName());
		logger.info(sql);

		Object[] args = new Object[] { 0, 9999 };

		List<ShipmentExt> rows = jdbcTemplate.query(sql, new ShipmentRowMapper(), args);

		sqlHelper.clear(args);

		return rows;
	}

	public ShipmentExt get(int id) {
		String sql = sqlHelper.sqlGet(null, getTableName());
		logger.info(sql);

		ShipmentExt ext = jdbcTemplate.queryForObject(sql, new ShipmentRowMapper(), id);

		return ext;
	}

	public int count() {
		String sql = sqlHelper.sqlCount(getTableName());
		logger.info(sql);
		int row = jdbcTemplate.queryForInt(sql);
		return row;
	}

	public boolean remove(int id) {
		String sql = sqlHelper.sqlRemove(getTableName());
		logger.info(sql);

		int affectRow = jdbcTemplate.update(sql, id);
		if (affectRow > 0) {
			return true;
		} else {
			return false;
		}
	}

	class ShipmentRowMapper implements RowMapper<ShipmentExt> {

		public ShipmentExt mapRow(ResultSet rs, int rowNum) throws SQLException {

			ShipmentExt t = new ShipmentExt();
			t.setId(rs.getInt("id"));
			t.setMedicineId(rs.getInt("medicineId"));
			t.setTime(rs.getLong("time"));
			t.setAmount(rs.getInt("amount"));
			return t;
		}

	}

	// =================================
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public SqlHelper getSqlHelper() {
		return sqlHelper;
	}

	public void setSqlHelper(SqlHelper sqlHelper) {
		this.sqlHelper = sqlHelper;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}
